package com.dps.omc.email;

import com.dps.omc.model.Emaillog;
import com.dps.omc.model.MailServer;
import com.dps.omc.service.IEmaillogService;
import com.dps.omc.service.IMailServerService;
import com.dps.omc.utils.StateConstants;
import com.dps.omc.utils.SysSetting;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by lip on 2016-04-03.
 */
@Service
public class EmailUtil {

    @Autowired
    private IMailServerService mailServerService;
    @Autowired
    private IEmaillogService emaillogService;
    private static final Integer RETURN_MSG_MAXSIZE = 2000;

    public void send(String toEmail,String subject,String msg)
    {
        String mailAble = SysSetting.getValue(StateConstants.MAIL_ABLE);
        if(mailAble!=null&&Integer.parseInt(mailAble)>0&&validEmailFormat(toEmail)) {
            this.sendMail(toEmail,subject,msg);
        }
    }

    private Boolean validEmailFormat(String toEmail)
    {
        if(toEmail.contains("@"))
        {
            return true;
        }
        return false;
    }

    private void sendMail(String toEmail,String subject,String msg)
    {
        MailServer mailServer = mailServerService.findAll().get(0);
        boolean isSSL = false;

        String host = mailServer.getSmtp();
        int port = Integer.parseInt(mailServer.getPort());
        String from = mailServer.getFromEmail();
        String to = toEmail;
        String username = mailServer.getUsername();
        String password = mailServer.getPassword();
        try {
            Email email = new SimpleEmail();
            email.setCharset("gb2312");
            email.setSSLOnConnect(isSSL);
            email.setHostName(host);
            email.setSmtpPort(port);
            email.setAuthentication(username, password);
            email.setFrom(from);
            email.addTo(to);
            email.setSubject(subject);
//            email.setMsg(msg);
            email.setContent(msg, "text/plain;charset=gb2312");
            email.send();
            this.recordEmail(from,toEmail,subject,msg);
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }

    private void recordEmail(String from,String toEmail,String subject,String content)  {

        Emaillog emaillog = new Emaillog();
        Integer MaxSize = RETURN_MSG_MAXSIZE;
        String contents = content.length()>MaxSize?content.substring(0,MaxSize):content;
        try {
            emaillog.setFromEmail(from);
            emaillog.setToEmail(toEmail);
            emaillog.setSubject(subject);
            emaillog.setContent(contents);
            emaillogService.add(emaillog);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
